<template>
  <div class="container">
    <!-- 表格 -->
    <el-table
      :data="tableList"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      highlight-current-row
      v-loading="loading"
      stripe
      style="border: 1px solid #dfe6ec"
    >
      <el-table-column
        prop="name"
        label="角色名称"
        :formatter="formatTd"
      ></el-table-column>
      <el-table-column
        prop="id"
        label="角色ID"
        :formatter="formatTd"
        width="400"
      ></el-table-column>
      <el-table-column
        prop="remark"
        label="角色介绍"
        :formatter="formatTd"
      ></el-table-column>
      <el-table-column label="操作" :formatter="formatTd">
        <template slot-scope="scope">
          <el-link
            type="primary"
            @click="deleteEvent(scope.row.id)"
            v-show="isShowDel"
            >删除</el-link
          >
          <span v-show="!isShowDel">--</span>
        </template>
      </el-table-column>
      <!-- 表格数据为空时，页面显示 -->
      <div slot="empty" v-show="isShow">
        <emptyTable emptyText="暂无相关信息"></emptyTable>
      </div>
    </el-table>
    <Pagination
      ref="pagination"
      @getList="getTableList"
      :requestUrl="requestUrl"
      :filterField="filterField"
    ></Pagination>
    <!-- 添加弹窗 -->
    <el-dialog
      title="添加角色"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      @close="closeDialog()"
      custom-class="dialog-minwidth"
      width="800px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        :model="roleForm"
        :rules="formRule"
        ref="roleForm"
        class="roleForm"
        v-if="roleList.length > 0"
      >
        <el-form-item label="" prop="role">
          <el-checkbox-group v-model="roleForm.role" @change="getCheckedRoles">
            <el-col :span="8" v-for="item in roleList" :key="item.code">
              <el-checkbox :label="item.id">{{ item.name }}</el-checkbox>
            </el-col>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <p v-if="roleList.length <= 0" class="emptyRole">未有尚未关联的角色</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog()" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          class="save"
          @click.native="saveRole()"
          :loading="isSaveLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'userRole',
  props: ['id'],
  data() {
    var checkRole = (rule, value, callback) => {
      if (value.length == 0) {
        return callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }
    return {
      tableList: [],
      requestUrl: 'api-u/users/rolelist',
      isShow: false, //列表加载
      loading: true,
      showDialog: false, //添加角色弹窗显示
      roleList: [],
      roleIds: [],
      roleForm: {
        role: [],
      },
      formRule: {
        role: [{ required: true, validator: checkRole, trigger: 'change' }],
      },
      //搜索条件
      filterField: {
        id: '',
      },
      isShowDel: '',
      isSaveLoading: false,
    }
  },
  created() {
    this.filterField.id = this.id
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('user:delete') > -1
  },
  methods: {
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    //删除
    deleteEvent(roleId) {
      this.$confirm('是否确认该条记录?', '删除记录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteRow(roleId)
        })
        .catch(() => {})
    },
    deleteRow(roleId) {
      this.axios({
        method: 'post',
        url: 'api-u/users/delrole',
        data: {
          id: this.id,
          roleId: roleId,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {}
        )
        .catch((error) => {})
    },
    //添加角色
    addRole() {
      this.roleForm.role = []
      this.getRole()
      this.showDialog = true
    },
    //关闭弹窗事件
    closeDialog() {
      this.showDialog = false
      this.$nextTick(function () {
        //this.$refs[formName].resetFields();
      })
    },
    //选定角色
    getCheckedRoles() {
      this.roleIds = this.roleForm.role
    },
    //保存角色
    saveRole() {
      this.isSaveLoading = true
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.saveAjax()
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    saveAjax() {
      this.axios({
        method: 'post',
        url: 'api-u/users/roles',
        data: {
          id: this.id,
          roleIds: this.packageParams(this.roleIds),
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              this.showDialog = false
              this.filterField.id = this.id
              this.$nextTick(function () {
                this.$refs.pagination.getTableListData()
                this.isSaveLoading = false
              })
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
              this.isSaveLoading = false
            }
          },
          (res) => {
            this.$message({
              message: '保存失败',
              type: 'error',
            })
            this.isSaveLoading = false
          }
        )
        .catch((error) => {
          this.$message({
            message: '保存失败',
            type: 'error',
          })
          this.isSaveLoading = false
        })
    },
    getRole() {
      this.axios({
        method: 'post',
        url: 'api-u/role/nothave',
        data: { userId: this.id },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.roleList = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
.container {
  margin: 24px;
  .roleForm {
    .el-col-8 {
      text-align: center;
      //margin-bottom: 24px;
    }
    /deep/.el-checkbox__label {
      float: right;
      line-height: 17px;
      width: 180px;
      overflow: hidden;
      text-align: left;
      white-space: normal;
      text-overflow: ellipsis;
      padding-top: 11px;
    }
  }
  .emptyRole {
    font-size: 18px;
    text-align: center;
  }
  /deep/ .el-form-item__content {
    line-height: 40px;
  }
}
</style>
